
import React, { useEffect, useState, useMemo, useRef } from "react";
import { message, Space } from "antd";
import { v4 as uuidv4 } from "uuid";
import axios from "axios";
import {
  useXAgent,
  useXChat,
  XRequest
} from "@ant-design/x";
import AttachmentInput from "../components/AttachmentInput/AttachmentInput.js";
import BubbleChat from "../components/BubbleChat/BubbleChat.jsx";
import WelcomeMessage from "../components/WelcomeMessage/WelcomeMessage.js";
import TipsPrompts from "../components/TipsPrompts/TipsPrompts.js";
import ConversationsManger from "../components/ConversationsManger/ConversationsManger.js";
import ContentRenderer from "../utils/ContentRenderer.jsx";
import { getToken } from "../utils/auth.js";
import useStyle from "../views/Index/index";
import {
  MenuFoldOutlined,
  MenuUnfoldOutlined,
  UploadOutlined,
  UserOutlined,
  VideoCameraOutlined, PlusOutlined
} from '@ant-design/icons';
import LogoNode from '../../src/components/LogoNode/LogoNode';
import { Button, Layout, Menu, theme } from 'antd';
const { Header, Sider, Content } = Layout;
import { createStyles, useResponsive } from 'antd-style';


// 渲染Markdown内容的函数
const RenderMarkdown = (content) => <ContentRenderer content={content} />;

// 定义API的基础URL和路径
const BASE_URL = process.env.REACT_APP_API_BASE_URL;
const PATH = process.env.REACT_APP_API_PATH;

const DefaultLayout = () => {
  const { styles } = useStyle();
  const [content, setContent] = useState("");
  const [conversationsItems, setConversationsItems] = useState([]);
  const [activeKey, setActiveKey] = useState("init");
  const [loading, setLoading] = useState(false);
  const [historyMessages, setHistoryMessages] = useState([]);
  const [conversationId, setConversationId] = useState(null);
  const [selectedModel, setSelectedModel] = useState(null);
  const abortRef = useRef(null);

  const [collapsed, setCollapsed] = useState(false);
  // 创建一个 ref 用于引用菜单元素
  const menuRef = useRef(null);
  const buttonRef = useRef(null);
  const {
    token: { colorBgContainer, borderRadiusLG },
  } = theme.useToken();

  // 初始化XAgent
  const [agent] = useXAgent({ baseURL: `${BASE_URL}${PATH}` });

  // 使用XChat钩子
  const { messages, setMessages } = useXChat({
    agent,
    requestPlaceholder: "等待中...",
    requestFallback: "忙碌中，请重试",
  });

  const messagesItems = useMemo(
    () =>
      messages.map(({ id, message, role }) => {
        return {
          key: id,
          loading: message === "等待中..." ? true : false,
          role: role === "user" ? "user" : "assistant",
          content: message,
        };
      }),
    [messages]
  );

  // 统一的API请求函数
  const fetchApi = async (endpoint, options = {}) => {
    try {
      const response = await axios.get(`${BASE_URL}${PATH}${endpoint}`, {
        headers: {
          Authorization: `Bearer ${getToken()}`
        },
        ...options
      });
      return response.data;
    } catch (error) {
      handleApiError(error);
      throw error;
    }
  };

  // 错误处理函数
  const handleApiError = (error) => {
    console.error("API Error:", error);
    const errorMessage = { 
      400: "忙碌中，请重试",
      401: "未授权，请登录后重试",
      404: "忙碌中，请重试",
      500: "忙碌中，请重试",
    }[error.response?.status] || "请登录后重试";
    message.error(errorMessage);
  };

  // 辅助函数：获取时间分组
const getTimeGroup = (date) => {
  const now = new Date();
  const todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime();
  const oneWeekAgo = todayStart - 6 * 24 * 60 * 60 * 1000; // 本周开始时间（含今天）

  const timestamp = date.getTime();
  
  if (timestamp >= todayStart) {
    return "今天";
  } else if (timestamp >= oneWeekAgo) {
    return "本周";
  } else {
    return "更早";
  }
};


  // 使用Effect钩子处理副作用
  useEffect(() => {
    const fetchData = async () => {
      if (activeKey === "init" || activeKey === "AddConversation") {
        try {
          const conversations = await fetchApi('/conversations');
          const formattedConversations = (conversations.data || []).map(conversation => ({
            key: conversation.conversation_id,
            label: conversation.title,
            updated_at:new Date(conversation.updated_at).getTime(), // 存储为时间戳,
            group: getTimeGroup(new Date(conversation.updated_at)),
          // })).sort((a, b) => new Date(b.updated_at) - new Date(a.updated_at));
          }));
          setConversationsItems(formattedConversations);
          if (formattedConversations.length > 0 && activeKey === "AddConversation") {
            setActiveKey(formattedConversations[0].key);
            setConversationId(formattedConversations[0].key);
          } else if (formattedConversations.length === 0) {
            setConversationsItems([]);
            setActiveKey(null);
            setConversationId(null);
          }
        } catch (error) {
          console.error('Error fetching conversations:', error);
        }
      }
    };

    fetchData();
  }, [activeKey]);

  // 请求聊天
  const fetchRequest = XRequest({
    baseURL: `${BASE_URL}${PATH}/chat`,
    fetch: (url, options) => {
      const controller = new AbortController();
      const signal = controller.signal;
      const timeoutId = setTimeout(() => controller.abort(), 300000); // 超时5分钟

      abortRef.current = () => controller.abort();

      return fetch(url, {
        method: "POST",
        body: options.body,
        headers: { Authorization: `Bearer ${getToken()}` },
        signal,
      })
        .then((response) => {
          clearTimeout(timeoutId);
          console.log("连接超时");
          return response;
        })
      // .catch((error) => {
      //   console.error("Fetch error:", error);
      // });
    },
  });


  // 请求聊天的异步函数
  const requestChat = async (question) => {
    const userMessage = { id: uuidv4(), message: question, role: "user" };
    const assistantMessage = { id: uuidv4(), message: "等待中...", role: "assistant" };

    setMessages((prev) => [...prev, userMessage, assistantMessage]);
    setHistoryMessages(prevHistory => [
      ...prevHistory,
      { id: userMessage.id, role: "user", content: question },

    ].slice(-21)  // 添加新消息并截取最后20个元素
    );

    setLoading(true);
    let AddConversation_flag = false;
    let newContent = '';
    try {
      await fetchRequest.create(
        {
          message: question,
          history: historyMessages,
          stream: true,
          model: selectedModel,
          conversation_id: conversationId,
        },
        {
          onUpdate: (response) => {
            if (conversationId === null && !AddConversation_flag) { // 检查标志变量
              setActiveKey("AddConversation");
              AddConversation_flag = true;
            }
            const data = JSON.parse(response.data);
            if (data.data[0].choices[0].delta.content) {
              newContent += data.data[0].choices[0].delta.content;
              setMessages(prevMessages =>
                prevMessages.map(msg =>
                  msg.id === assistantMessage.id
                    ? { ...msg, message: <ContentRenderer content={newContent} /> }
                    : msg
                )
              );

              setHistoryMessages(prevHistory => {
                // 检查是否已经存在 assistantMessage.id 的消息
                const assistantMessageExists = prevHistory.some(msg => msg.id === assistantMessage.id);

                if (assistantMessageExists) {
                  // 如果存在，更新现有消息的内容
                  return prevHistory.map(msg =>
                    msg.id === assistantMessage.id
                      ? { ...msg, content: newContent }
                      : msg
                  );
                } else {
                  // 如果不存在，添加新的消息对象
                  return [...prevHistory, { id: assistantMessage.id, role: "assistant", content: newContent }];
                }
              });
            }
          },
          onSuccess: () => {
            setLoading(false);
          },
        }
      );
    } catch (error) {
      if (error.name === 'AbortError') {
        setMessages(prevMessages =>
          prevMessages.map(msg =>
            msg.id === assistantMessage.id
              ? { ...msg, message: RenderMarkdown(newContent + "\n\n **_本次回答已被终止_**") }
              : msg
          )
        );
      } else {
        console.error("请求有错误！", error);
        setLoading(false);

        handleApiError(error);
      };
    }
  };

  const onSubmit = (nextContent) => {
    if (!nextContent) return;
    requestChat(nextContent);
    setContent('');  //清空输入框
    setLoading(true); // 显示发送按钮 loading 状态
  };

  const onCancel = () => {
    if (abortRef.current) abortRef.current();
    setLoading(false);
  };

  const handlePromptsItemClick = (info) => {
    onSubmit(info.data.description);
    setHistoryMessages([]); // 清空历史消息
    setContent(''); //清空输入框
  };

  const getMessage = async (conversationId) => {
    try {
      const conversationDetails = await fetchApi(`/conversations/${conversationId}`);
      const formattedMessages = conversationDetails.data?.map(msg => ({
        id: msg.message_id,
        message: msg.sender_type === "user" ? msg.content : <ContentRenderer content={msg.content} animate={false} />,
        role: msg.sender_type,
      })) || [];
      setMessages(formattedMessages);
    } catch (error) {
      console.error('Error fetching conversation details:', error);
      // 可以添加更多的错误处理逻辑，例如显示错误信息给用户或重试机制
    }
  }

  const onConversationClick = (key) => {
    if (loading || key === conversationId) return;

    setActiveKey(key);
    setConversationId(key);
    setHistoryMessages([]); // 清空历史消息
    getMessage(key);
  }


  const onAddConversation = () => {
    if (messages.length !== 0 && loading === false) {
      setMessages([]); // 清空当前消息
      setHistoryMessages([]); // 清空当前历史消息
      setConversationId(null); // 清空当前会话ID
      setActiveKey(null); // 清空当前激活会话ID
    }
    else if (loading === true) {
    }
    else {
      message.info("已是最新会话");
    }
  };


  const placeholderNode = (
    <div>
      <Space direction="vertical" size={16} className={styles.placeholder}>
        <WelcomeMessage className={styles.placeholder} />
        <TipsPrompts onPromptsItemClick={handlePromptsItemClick} />
      </Space>
    </div>
  );

  // 增加移动端头部
  const MobileHeader = () => {
    const { styles } = useStyle();
    return (
      <div className={styles.mobileHeader}  >
        <Button
          type="text"
          icon={collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
          onClick={clickcollapsed}
        />
        <span style={{ marginLeft: 8 }}>{process.env.REACT_APP_APP_NAME}</span>
      </div>

    );
  };

  // 获取响应式断点状态
  const responsive = useResponsive(); // { mobile: boolean, tablet: boolean, desktop: boolean }
  // 使用示例
  const isMobile = responsive.mobile; // 判断是否是移动端
  // 处理全局点击事件
  const handleGlobalClick = (event) => {
    // 判断点击事件的目标元素是否在菜单元素之外
    if (menuRef.current && !menuRef.current.contains(event.target)) {
      setCollapsed(true);
    }
  };
  // 移动端默认折叠侧边栏
  useEffect(() => {
    if (responsive.mobile) {
      setCollapsed(true);
    } else {
      setCollapsed(false);
    }
    ;
  }, [responsive.mobile]);
  // 使用 useEffect 监听全局点击事件
  useEffect(() => {
    if (responsive.mobile) {
      // 添加全局点击事件监听器
      window.addEventListener('click', handleGlobalClick);
      // 在组件卸载时移除事件监听器，避免内存泄漏
      return () => {
        window.removeEventListener('click', handleGlobalClick);
      };
    }

  }, [responsive.mobile]);
  // 添加延时器
  const clickcollapsed = () => {
    setTimeout(() => {
      setCollapsed(!collapsed)
    }, 20);
  };
  const handleChatClick = () => {
    if (responsive.mobile) {
      setCollapsed(true);
    }
  };


  return (

    <Layout className={styles.layout}>
      {/* 移动端专用头部 */}
      <MobileHeader />
      <Sider
        theme="light"
        ref={menuRef}
        collapsible
        collapsed={collapsed}
        data-collapsed={collapsed} // 传递折叠状态
        onCollapse={(value) => setCollapsed(value)}
        trigger={null} // 隐藏默认触发器
        width={250}
        collapsedWidth={0}
        style={{
          overflowX: 'auto',
          height: '100vh',
          position: 'fixed',
          left: 0,
          zIndex: 2,
          backgroundColor: '#F8F8F8',
          transition: 'none'
        }}
        className={styles.mobileSider}
      >
        <div className={styles.fixedHeadLogo}>
          <LogoNode />
          {/* 🌟 添加会话 */}
          <Button
            onClick={onAddConversation}
            type="link"
            className={styles.addBtn}
            icon={<PlusOutlined />}
          >
            新增会话
          </Button>
        </div>
        <div className={styles.ScroollMenu}>
          <ConversationsManger
            className={styles.menuScroll}
            onAddConversation={onAddConversation}
            onConversationClick={onConversationClick}
            conversationsItems={conversationsItems}
            activeKey={activeKey}
            collapsed={collapsed} // 可以根据折叠状态调整内部样式
            setConversationsItems={setConversationsItems}
            setActiveKey={setActiveKey}
          />
        </div>

      </Sider>
      <Layout className={styles.mobileLayout} style={{ marginLeft: collapsed ? 5 : 250 }}>
        <Header
          style={{
            padding: 0,
            background: colorBgContainer,
            position: 'sticky',
            top: 0,
            zIndex: 1,
            height: 48
          }}
        >
          <Button
            type="text"

            icon={collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
            onClick={() => setCollapsed(!collapsed)}
          // style={{
          //   fontSize: '16px',
          //   width: 34,
          //   height: 34,
          // }}
          />
        </Header>
        <div className={styles.layout}>
          <div className={styles.chat}>
            <Content className={styles.messages}>
              <BubbleChat
                items={messagesItems}
                placeholderNode={placeholderNode}
                RenderMarkdown={RenderMarkdown}
              />

            </Content>
            <div className={styles.footer}>
              <AttachmentInput
                styles={styles}
                onSubmit={onSubmit}
                content={content}
                setContent={setContent}
                loading={loading}
                setLoading={setLoading}
                onCancel={onCancel}
              />
            </div>
          </div>
        </div>
      </Layout>
    </Layout>
  );
};

export default DefaultLayout;